$(function () {
    new AjaxUpload('#upload', {
        action: baseURL + "sys/upload/imgUpload",
        name: 'imgFile',
        autoSubmit: true,
        responseType: "json",
        onComplete: function (file, r) {
            if (r.code == 0) {
                alert("图片上传成功！！");
                // $("#bingimg").attr('src', r.url);
                vm.btCustomerProBaseinfo.imgs +=";"+ r.url;
                if( vm.btCustomerProBaseinfo.imgs[0]==";"){
                    vm.btCustomerProBaseinfo.imgs=  vm.btCustomerProBaseinfo.imgs.substr(1);
                }
                vm.imgarr= vm.btCustomerProBaseinfo.imgs.split(";");
            } else {
                alert(r.msg);
            }
        }
    });
    $(".tab-content").hide();
    $("ul.tab-head li:first").addClass("active").show();
    $(".tab-content:first").show();
});
//初始化表格
var creatjqg;
function creatjqGrid() {
    creatjqg= $("#jqGrid").jqGrid({
        url: baseURL + 'sys/btcustomerprobaseinfo/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: 'id', width: 50, key: true },

            { label: '产品名称', name: 'title', index: 'title', width: 80 },


            { label: '招生对象描述', name: 'zsdxDesc', index: 'zsdx_desc', width: 80 },

            { label: '行程描述', name: 'xcDesc', index: 'xc_desc', width: 80 },

            { label: '举办城市描述', name: 'zbcsDesc', index: 'zbcs_desc', width: 80 },

            { label: '出发城市描述', name: 'cfcsDesc', index: 'cfcs_desc', width: 80 },

            { label: '活动主题描述', name: 'hdztDesc', index: 'hdzt_desc', width: 80 }


        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        postData:{'navbarid':vm.clickTreeNode.id},
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
}
//富文本
var editor;
//文本编辑器
function kedit(kedit) {
    editor = KindEditor.create(kedit, {
        width: '1400px',
        height: '600px',
        resizeMode: 0,
        allowPreviewEmoticons: false,
        allowImageUpload: true,//允许上传图片
        allowFileManager: true, //允许对上传图片进行管理
        uploadJson: baseURL+'sys/upload/imgUpload', //上传图片的java代码
        fileManagerJson: baseURL+'/upload/fileManager',
        afterUpload: function () {
            this.sync();
        }, //图片上传后，将上传内容同步到textarea中
        afterBlur: function () {
            this.sync();
        }, //失去焦点时，将上传内容同步到textarea中

        items: [
            'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'cut', 'copy', 'paste',
            'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
            'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
            'superscript', 'clearhtml', 'selectall', '|', 'fullscreen', '/',
            'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
            'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
            'table', 'hr', 'emoticons', 'baidumap','media'
        ]
    });
};
//ztree基本配置
var Category_ztree;
var CategoryZtree_setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pid",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    check: {
        enable: false,
        nocheckInherit: true
    },
    callback: {
        onClick: zTreeOnClick
    }
};

function zTreeOnClick(event, treeId, treeNode, clickFlag) {
    vm.clickZtreeNode(treeNode);
}
function getsubcatag(id,cname,findsub) {
    $.ajax({
        type: "POST",
        url: baseURL + "sys/catagroyManager/getsubcataandchild",
        async:true,
        data: {pid:id,cname:cname,findsub:findsub},
        success: function(r){
            if(r.code === 0){
                 vm.themecatag = r.themecatag;
                 vm.yingqicatag = r.yingqicatag;
                 vm.zbcitycatag = r.zbcitycatag;
                 vm.zsdxcatagag = r.zsdxcatagag;
                 $("#cfcs").hide();
                 if(r.hasOwnProperty("yxgjcatag")){
                     vm.yxgjcatag = r.yxgjcatag;
                     $("#cfcs").show();
                 }
            }else{
                alert(r.msg);
            }
        }
    });

}
var vm = new Vue({
	el:'#rrapp',
	data:{
		title: null,
        clickTreeNode:{},
        categdata:{},
        q:{
            name:""
        },
        btCustomerProYinqi:{},
        btCustomerProBaseinfo:{},
        maincatagroy :{},
        imgarr:[],
        themecatag :{},
        yingqicatag:{},
        zbcitycatag:{},
        yxgjcatag:{},
        zsdxcatagag:{},
        outlinearr:["","",""],
        btCustomerProDetail:{}

	},
	methods: {
        getCouponSelected:function(ele){
            //获取选中
            var optionTxt = $(ele.target).find("option:selected").text();
            var optionVal = ele.target.value;
            if(optionVal=='0'){
                return;
            }

            /** 这里写的，我就日狗了，没有想起好法**/
            $("#cfcs").hide();
          /*  if(optionTxt.indexOf("国际")>0){
                getsubcatag(optionVal,"出发",false);
                $("#cfcs").show();
            }*/
           getsubcatag(optionVal,"主题",true);

           vm.btCustomerProBaseinfo.zflId = optionVal;
           vm.btCustomerProBaseinfo.zflDesc = optionTxt;
        },
        getHDZTSelected:function (ele) {
            var optionTxt = $(ele.target).find("option:selected").text();
            var optionVal = ele.target.value;
            if(optionVal=='0'){
                return;
            }
            if(optionVal=='-1'){
                vm.btCustomerProBaseinfo.hdztIds='';
                vm.btCustomerProBaseinfo.hdztDesc='';
                return;
            }
            vm.btCustomerProBaseinfo.hdztIds +=";"+optionVal
            if( vm.btCustomerProBaseinfo.hdztIds[0]==";"){
                vm.btCustomerProBaseinfo.hdztIds=  vm.btCustomerProBaseinfo.hdztIds.substr(1);
            }
            vm.btCustomerProBaseinfo.hdztDesc +=";"+optionTxt
            if( vm.btCustomerProBaseinfo.hdztDesc[0]==";"){
                vm.btCustomerProBaseinfo.hdztDesc=  vm.btCustomerProBaseinfo.hdztDesc.substr(1);
            }
        },
        getYXGJelected:function (ele) {
            var optionTxt = $(ele.target).find("option:selected").text();
            var optionVal = ele.target.value;
            if(optionVal=='0'){
                return;
            }
            if(optionVal=='-1'){
                vm.btCustomerProBaseinfo.cfcsIds='';
                vm.btCustomerProBaseinfo.cfcsDesc='';
                return;
            }
            vm.btCustomerProBaseinfo.cfcsIds +=";"+optionVal
            if( vm.btCustomerProBaseinfo.cfcsIds[0]==";"){
                vm.btCustomerProBaseinfo.cfcsIds=  vm.btCustomerProBaseinfo.cfcsIds.substr(1);
            }
            vm.btCustomerProBaseinfo.cfcsDesc +=";"+optionTxt
            if( vm.btCustomerProBaseinfo.cfcsDesc[0]==";"){
                vm.btCustomerProBaseinfo.cfcsDesc=  vm.btCustomerProBaseinfo.cfcsDesc.substr(1);
            }
        },
        getJBCSSelected:function (ele) {
            var optionTxt = $(ele.target).find("option:selected").text();
            var optionVal = ele.target.value;
            if(optionVal=='0'){
                return;
            }
            if(optionVal=='-1'){
                vm.btCustomerProBaseinfo.zbcsIds='';
                vm.btCustomerProBaseinfo.zbcsDesc='';
                return;
            }
            vm.btCustomerProBaseinfo.zbcsIds +=";"+optionVal
            if( vm.btCustomerProBaseinfo.zbcsIds[0]==";"){
                vm.btCustomerProBaseinfo.zbcsIds=  vm.btCustomerProBaseinfo.zbcsIds.substr(1);
            }
            vm.btCustomerProBaseinfo.zbcsDesc +=";"+optionTxt
            if( vm.btCustomerProBaseinfo.zbcsDesc[0]==";"){
                vm.btCustomerProBaseinfo.zbcsDesc=  vm.btCustomerProBaseinfo.zbcsDesc.substr(1);
            }
        },
        getYQSelected:function (ele) {
            var optionTxt = $(ele.target).find("option:selected").text();
            var optionVal = ele.target.value;
            if(optionVal=='0'){
                return;
            }
            vm.btCustomerProBaseinfo.xcIds = optionVal;
            vm.btCustomerProBaseinfo.xcDesc = optionTxt;
        },
        getZSDXSelected:function (ele) {
            var optionTxt = $(ele.target).find("option:selected").text();
            var optionVal = ele.target.value;
            if(optionVal=='0'){
                return;
            }
            vm.btCustomerProBaseinfo.zsdxIds = optionVal;
            vm.btCustomerProBaseinfo.zsdxDesc = optionTxt;
        },
        deleteimg:function (img) {
            vm.imgarr.splice(vm.imgarr.indexOf(img),1);
            vm.btProductDetail.proImg=vm.imgarr.join(';');
        },
		query: function () {
			vm.reload();
		},
        //列表操作 b
		add: function(){
            $("#showtable").hide();
            $("#unshowtable").hide();
            $("#addormod").show();
            vm.imgarr=[];
            vm.btCustomerProBaseinfo = {imgs:"",zbcsIds:"",zbcsDesc:"",hdztIds:"",hdztDesc:"",cfcsIds:"",cfcsDesc:""};
			vm.title = "添加新课程";

            $.get(baseURL + "sys/catagroyManager/getmaincatagroy", function(r){
                vm.maincatagroy = r.maincatagroy;
            });
            var t;
            clearTimeout(t);
            KindEditor.remove('textarea[name="contentDetail"]');
            t = setTimeout(function (){
                kedit('textarea[name="contentDetail"]');
            }, 500);
		},
		update: function (event) {

			var id = getSelectedRow();
			if(id == null){
				return ;
			}
            $("#showtable").hide();
            $("#unshowtable").hide();
            $("#addormod").show();
            vm.title = "修改";
            
            vm.getInfo(id);
            $.get(baseURL + "sys/catagroyManager/getmaincatagroy", function(r){
                vm.maincatagroy = r.maincatagroy;
            });
		},
		saveOrUpdate: function (event) {
			var url = vm.btCustomerProBaseinfo.id == null ? "sys/btcustomerprobaseinfo/save" : "sys/btcustomerprobaseinfo/update";
            if(vm.btCustomerProBaseinfo.imgs==""){
                alert("请上传课程图片");
                return;
            }
			if(vm.btCustomerProBaseinfo.hdztIds==""){
			    alert("请选着活动主题");
			    return;
            }
            if(vm.btCustomerProBaseinfo.zbcsIds==""){
                alert("请选着主办城市");
                return;
            }
            if(!vm.btCustomerProBaseinfo.hasOwnProperty("xcIds")){
                alert("请选着营期");
                return;
            }
            if(!vm.btCustomerProBaseinfo.hasOwnProperty("zsdxIds")){
                alert("请选着招生对象");
                return;
            }
            vm.btCustomerProBaseinfo.navbarid = vm.clickTreeNode.id;
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.btCustomerProBaseinfo),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
                            vm.btCustomerProBaseinfo.id = r.pkey;
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
        saveOrUpdateParam:function () {
		    if(!vm.btCustomerProBaseinfo.hasOwnProperty("id")){
		        alert("请先填写基本信息并交");
		        return;
            }
            vm.btCustomerProBaseinfo.outline=vm.outlinearr[0]+";"+vm.outlinearr[1]+";"+vm.outlinearr[2]
            $.ajax({
                type: "POST",
                url: baseURL + "sys/btcustomerprobaseinfo/saveparam",
                contentType: "application/json",
                data: JSON.stringify(vm.btCustomerProBaseinfo),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){

                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        saveOrUpdateDetail:function () {
            if(!vm.btCustomerProBaseinfo.hasOwnProperty("id")){
                alert("请先填写基本信息并交");
                return;
            }
            var url = vm.btCustomerProDetail.id == null ? "sys/btcustomerprodetail/save" : "sys/btcustomerprodetail/update";
            vm.btCustomerProDetail.proId = vm.btCustomerProBaseinfo.id;
            vm.btCustomerProDetail.context = encodeURIComponent($("#activity_detail").val());
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.btCustomerProDetail),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.btCustomerProDetail.id =r.pkey;
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/btnavbar/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "sys/btcustomerprobaseinfo/info/"+id, function(r){
                vm.btCustomerProBaseinfo = r.btCustomerProBaseinfo;
                if(vm.btCustomerProBaseinfo.imgs==null|| vm.btCustomerProBaseinfo.imgs==""){
                    vm.imgarr=null;
                    vm.btCustomerProBaseinfo.imgs=""
                }else{
                    vm.imgarr= vm.btCustomerProBaseinfo.imgs.split(";");
                }
                vm.outlinearr = vm.btCustomerProBaseinfo.outline.split(";");
                $.get(baseURL + "sys/btcustomerprodetail/info/"+vm.btCustomerProBaseinfo.id, function(r){
                    if(!r.hasOwnProperty("btCustomerProDetail")|| r.btCustomerProDetail==null){
                        r.btCustomerProDetail={};
                        r.btCustomerProDetail.proId="";
                        r.btCustomerProDetail.context="";
                    }
                    vm.btCustomerProDetail = r.btCustomerProDetail;
                    var t;
                    clearTimeout(t);
                    KindEditor.remove('textarea[name="contentDetail"]');
                    t = setTimeout(function (){
                        kedit('textarea[name="contentDetail"]');
                    }, 500);
                });
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
        //列表操作 e
		// ztree 操作
        addcategroy:function () {
            var str = "添加分类";
            var id="#categadd";
            vm.addormodprocate(str,id,1);
        },
        modcategroy:function () {
            var str = "修改分类";
            var id="#categgmod";
            vm.addormodprocate(str,id,2);
        },
        delcategroy:function () {
            if(vm.clickTreeNode.children!= null && vm.clickTreeNode.children.length>0){
                alert('包含子分类不能删除', function (index3) {});
                return;
            }
            $.get(baseURL + "sys/btnavbar/iscandelete/" + vm.clickTreeNode.id, function (r) {
                if (r.code == 0) {
                    alert("该分类中有内容不能删除!!!", function (index3) {return;});
                }else{
                    confirm('确定要删除选中的记录？', function(){
                        $.get(baseURL + "sys/btnavbar/delcategroy/" +vm.clickTreeNode.id , function (r) {
                            if (r.code == 0) {
                                alert("删除成功！");
                                vm.getZTreeDateAndShow();
                            }else{
                                alert("删除失败！");
                            }
                        })
                    });
                }
            })
        },
        clickZtreeNode: function (treeNode) {
            $("#pcmod").show();
            $("#pcdel").show();
            $("#pcadd").show();
            vm.clickTreeNode = treeNode;
            if(vm.clickTreeNode .pid==-1){
                $("#pcdel").hide();
                $("#pcmod").hide();
            }else{
                $("#pcadd").hide();
            }
            vm.showRightDiv(treeNode)
        },
        showRightDiv:function (treeNode) {
            vm.title = treeNode.name;
            $("#showtable").hide();
            $("#unshowtable").hide();
            $("#addormod").hide();
            if(treeNode.pid!="-1"&& treeNode.hasOwnProperty("children")){
                $("#unshowtable").show();
                $("#unshowtable>strong").html("请点击子分类查看课程！！")
            }else if(treeNode.pid!="-1"&& !treeNode.hasOwnProperty("children")) {
                $("#showtable").show();
                vm.productlist(treeNode.id);
            }else{
                $("#unshowtable").show();
                $("#unshowtable>strong").html("请点击子分类查看课程！！")
            }
        },
        productlist:function () {
            if(creatjqg == null){
                creatjqGrid();
            }else{
                var page = $("#jqGrid").jqGrid('getGridParam','page');
                $("#jqGrid").jqGrid('setGridParam',{
                    postData:{'navbarid':vm.clickTreeNode.id},
                    page:page
                }).trigger("reloadGrid");
            }
        },
        addormodprocate:function(title,id,style){
            index3 = layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title:title ,
                area: ['560px', '350px'],
                shadeClose: false,
                content: jQuery(id)
                , btn: ['提交', '取消']
                , yes: function (index, layero) {
                    if(style==1){
                        vm.categdata.pid = vm.clickTreeNode.id;
                        vm.categdata.name =$("#newname").val();
                    }else if(style==2){
                        vm.categdata.pid = vm.clickTreeNode.pid;
                        vm.categdata.id = vm.clickTreeNode.id;
                        vm.categdata.name =$("#oldname").val();
                    }
                    if (vm.categdata.name != null && vm.categdata.name != "") {
                        //添加日志
                        $.ajax({
                            type: "POST",
                            url: baseURL + "sys/btnavbar/addormodcategroy",
                            contentType: "application/json",
                            data: JSON.stringify(vm.categdata),
                            success: function (r) {
                                if (r.code === 0) {
                                    layer.close(index3);
                                    alert('操作成功', function (index3) {
                                        vm.getZTreeDateAndShow();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    } else {
                        alert("日志不能为空!!!");
                    }
                }, btn2: function (index, layero) {
                    layer.close(index);
                    return false;
                }
                , cancel: function () {
                    //右上角关闭回调
                }
            });
        },
        getZTreeDateAndShow: function () {
            //加载菜单树
            $.get(baseURL + "sys/catagroyManager/getcategoryztree", function (r) {
                if (r.code == 0) {
                    Category_ztree = $.fn.zTree.init($("#CategoryZtree"), CategoryZtree_setting, r.categroyztree);
                    //展开所有节点
                    Category_ztree.expandAll(true);
                    //调用默认展开第一个结点
                    var nodes = Category_ztree.getNodes();
                    var childNodes = Category_ztree.transformToArray(nodes[0]);
                    Category_ztree.checkNode(childNodes[0], true, true);
                    Category_ztree.selectNode(childNodes[0]); //选中第一个父节点下面第一个子节点
                    Category_ztree.setting.callback.onClick(null, Category_ztree.setting.treeId, childNodes[0]);//点击第一个父节点下面第一个子节点
                }
            });
        }
        // ztree 操作e
	},
    mounted: function () {
        this.getZTreeDateAndShow();
    }
});
 //标签页
$("ul.tab-head li").click(function () {
    $("ul.tab-head li").removeClass("active");
    $(this).addClass("active");
    $(".tab-content").hide();

    var activeTab = $(this).find("a").attr("name");
    $(activeTab).fadeIn();
    return false;
});